using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Playables;

namespace GameDesigner
{
    public class PlayableStateMachineView : AnimatorStateMachineView
    {
        private PlayableGraph graph;
        private AnimationLayerMixerPlayable animationLayerMixer;

        public override void Init(params object[] args)
        {
            controller.View = this;
            graph = PlayableGraph.Create(name);
            var output = AnimationPlayableOutput.Create(graph, "Animation Output", animator);
            animationLayerMixer = AnimationLayerMixerPlayable.Create(graph);
            output.SetSourcePlayable(animationLayerMixer);
            for (int i = 0; i < controller.layers.Length; i++)
            {
                var layer = controller.layers[i];
                layer.stateMachine.Controller = controller;
                layer.stateMachine.Layer = layer;
                layer.stateMachine.Handler = new PlayableStateMachine(animator, graph, animationLayerMixer, layer);
                layer.stateMachine.Init();
            }
            graph.Play();
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            if (graph.IsValid())
                graph.Destroy();
        }

#if UNITY_EDITOR
        public override float GetAnimClipLength(StateAction action)
        {
            if (action.clipAsset is AnimationClip clip)
                return clip.length;
            return GetAnimClipLength(animator, action);
        }
#endif
    }
}